package com.greatwideweb.sandbox;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.util.Log;


public class MediaPlayerTask extends AsyncTask<String, Void, MediaPlayer> {

  ArrayList<IMediaPlayerTask> observers=new ArrayList<IMediaPlayerTask>();
  public void registerObserver(IMediaPlayerTask observer) {
    observers.add(observer);
  }
  
  public void notifyObservers(MediaPlayer mp) {
    for (IMediaPlayerTask iTask : observers) {
      iTask.onMediaPlayerComplete(mp);
    }
  }
  
  public void notifyError() {
    for (IMediaPlayerTask iTask : observers) {
      iTask.onMediaPlayerError();
    }
  }
  
  @Override
  protected MediaPlayer doInBackground(String... params)  {
    Log.d("doInBackground", "arg0: " + params[0]);
    // TODO Auto-generated method stub
    MediaPlayer mp = new MediaPlayer();
    PlsParser plsParser =null;
    try{
      plsParser = new PlsParser(params[0]);
    }catch(Exception e){
      ;
    }
    
    if(plsParser != null) {
      
      List<String> urls = plsParser.getUrls();
      boolean result = false;
      for (String s : urls) {
        result = isLegitAudioFeed(mp, s);
        Log.d("doInBackground", "result: " + result);
        if(result)
          break;
      }
      
      return mp;
      
    }else {
      return null;
    }
    
  }

  @Override
  protected void onPostExecute(MediaPlayer result) {
    // TODO Auto-generated method stub
    super.onPostExecute(result);
    if(result ==null)
      notifyError();
    else
      notifyObservers(result);
  }
  
  public boolean isLegitAudioFeed(MediaPlayer mp, String url){
    //set up MediaPlayer    
    
    boolean isInit = true;
 
    try {
        mp.setDataSource(url);
        mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        isInit=false;
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        isInit=false;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        isInit=false;
    }
    try {
        mp.prepare();
      //mp.prepareAsync();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
      Log.d("initAudio", "IllegalStateException");
        e.printStackTrace();
        isInit=false;
    } 
    
    catch (IOException e) {
        // TODO Auto-generated catch block
      Log.d("initAudio", "IOException");
        e.printStackTrace();
        isInit=false;
    }
    
    return isInit;
    
    
}

}
